//
//  GOUtility.m
//  GO2O
//
//  Created by yemeihua on 15/12/29.
//  Copyright © 2015年 yemeihua. All rights reserved.
//

#import "GOUtility.h"
#import <AVFoundation/AVFoundation.h>
#import <zlib.h>

CGFloat GOScreenScale() {
    static CGFloat scale;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        scale = [UIScreen mainScreen].scale;
    });
    return scale;
}

void GOCGContextAddRoundedRect(CGContextRef c, CGRect rect, CGFloat radius)
{
    int minX = rect.origin.x  ,
    maxX = minX + rect.size.width,
    midX = minX + rect.size.width / 2,
    
    minY = rect.origin.y ,
    maxY = minY + rect.size.height,
    midY = minY + rect.size.height / 2;
    
    CGContextMoveToPoint(c, minX, midY);
    CGContextAddArcToPoint(c, minX, minY, midX, minY, radius);
    CGContextAddArcToPoint(c, maxX, minY, maxX, midY, radius);
    CGContextAddArcToPoint(c, maxX, maxY, midX, maxY, radius);
    CGContextAddArcToPoint(c, minX, maxY, minX, midY, radius);
    CGContextClosePath(c);
}

CGRect GOFixCGRect(CGRect rect)
{
    rect.origin.x = floor(rect.origin.x);
    rect.origin.y = floor(rect.origin.y);
    rect.size.width = floor(rect.size.width);
    rect.size.height = floor(rect.size.height);
    return rect;
}

CGPoint GOFixCGPoint(CGPoint point)
{
    point.x = floor(point.x);
    point.y = floor(point.y);
    return point;
}



@implementation GOUtility

+ (NSURL *)convert2Mp4:(NSURL *)movUrl
{
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality])
    {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset
                                                                               presetName:AVAssetExportPresetHighestQuality];
        mp4Url = [movUrl copy];
        mp4Url = [mp4Url URLByDeletingPathExtension];
        mp4Url = [mp4Url URLByAppendingPathExtension:@"mp4"];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status])
            {
                case AVAssetExportSessionStatusFailed:
                    YCLog(@"failed, error:%@.", exportSession.error);
                    break;
                case AVAssetExportSessionStatusCancelled:
                    YCLog(@"cancelled.");
                    break;
                case AVAssetExportSessionStatusCompleted:
                    YCLog(@"completed.");
                    break;
                default:
                    YCLog(@"others.");
                    break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout)
        {
            YCLog(@"timeout.");
        }
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }
    
    return mp4Url;
}


//create Label
+(UILabel *)creatLabel:(CGRect)frame textcolor:(UIColor*)color text:(NSString *)str fontsize:(CGFloat)size
{
    UILabel *label = [[UILabel alloc]initWithFrame:frame];
    label.textColor = color;
    label.text = str;
    label.font = [UIFont systemFontOfSize:size];
    return label;
}

//create UIImageView
+(UIImageView *)creatImgView:(CGRect)frame imageName:(NSString *)imgName
{
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:frame];
    imgView.image = [UIImage imageNamed:imgName];
    imgView.userInteractionEnabled = YES;
    return imgView;
}

//create UIButton
+(UIButton *)createButton:(CGRect)frame title:(NSString *)title image:(NSString *)imageStr target:(id)target selector:(SEL)selector
{
    UIButton * button=[UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:imageStr];
    [button setImage:image forState:UIControlStateNormal];
    button.frame=frame;
    CGRect newFrame=frame;
    newFrame.origin.y=frame.size.height - 20;
    newFrame.size.height=frame.size.height/2.0;
    
    if ([title isEqualToString:@"扫码"]) {
        newFrame.origin.x= 17;
    }else
        newFrame.origin.x= 0;
    
    UILabel * label=[[UILabel alloc]initWithFrame:newFrame];
    label.text=title;
    [label setTextColor:[UIColor whiteColor]];
    label.textAlignment = NSTextAlignmentCenter;
    [button addSubview:label];
    label.font=[UIFont systemFontOfSize:10];
    label.backgroundColor=[UIColor clearColor];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    button.showsTouchWhenHighlighted = YES;
    return button;
}

//压缩数据
+ (NSData *)compressData:(NSData *)uncompressedData
{
    if ([uncompressedData length] == 0) return uncompressedData;
    
    z_stream strm;
    
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.total_out = 0;
    strm.next_in=(Bytef *)[uncompressedData bytes];
    strm.avail_in = (unsigned int)[uncompressedData length];
    
    if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil;
    
    NSMutableData *compressed = [NSMutableData dataWithLength:16384];  // 16K chunks for expansion
    
    do {
        
        if (strm.total_out >= [compressed length])
            [compressed increaseLengthBy: 16384];
        
        strm.next_out = [compressed mutableBytes] + strm.total_out;
        strm.avail_out = (unsigned int)([compressed length] - strm.total_out);
        
        deflate(&strm, Z_FINISH);
        
    } while (strm.avail_out == 0);
    
    deflateEnd(&strm);
    
    [compressed setLength: strm.total_out];
    return [NSData dataWithData:compressed];
}

//解压缩zip数据
+ (NSData *)uncompressZippedData:(NSData *)compressedData
{
    if ([compressedData length] == 0) return compressedData;
    
    unsigned full_length = [compressedData length];
    
    unsigned half_length = [compressedData length] / 2;
    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;
    z_stream strm;
    strm.next_in = (Bytef *)[compressedData bytes];
    strm.avail_in = [compressedData length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;
    while (!done) {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length]) {
            [decompressed increaseLengthBy: half_length];
        }
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = [decompressed length] - strm.total_out;
        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) {
            done = YES;
        } else if (status != Z_OK) {
            break;
        }
        
    }
    if (inflateEnd (&strm) != Z_OK) return nil;
    // Set real length.
    if (done) {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    } else {
        return nil;
    }
}



@end
